<template>
  <div>
    <el-card>
      <div slot="header">
        <el-button type="primary" icon="el-icon-plus" @click="add">添加规则</el-button>
        <el-button type="danger" size="small" @click="batchDelete">删除</el-button>
      </div>
      <!-- 主体部分的表格 -->
      <el-table :data="tableData" style="width: 100%" :current-row-key="tableData.id">
        <el-table-column type="index" label="编号" width="50"></el-table-column>
        <el-table-column label="学期">
          <template slot-scope="slotProps">{{slotProps.row.name}}</template>
        </el-table-column>
        <el-table-column label="时间">
          <template slot-scope="slotProps">{{slotProps.row.startDate}} 到 {{slotProps.row.endDate}}</template>
        </el-table-column>
        <!-- <el-table-column label="是否已生成计划">
          <template slot-scope="slotProps">{{slotProps.row.generateStatus}}</template>
        </el-table-column>-->
        <el-table-column label="操作" width="160">
          <template slot-scope="slotProps">
            <el-button
              type="primary"
              size="mini"
              title="编辑"
              icon="el-icon-edit"
              @click="edit(slotProps.$index)"
            ></el-button>
            <el-popover placement="top" width="160" v-model="visible2">
              <p>这是一段内容这是一段内容确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
                <el-button type="primary" size="mini" @click="del(slotProps.$index)">确定</el-button>
              </div>
              <el-button
                type="danger"
                size="mini"
                title="删除"
                icon="el-icon-delete"
                slot="reference"
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <!-- 底部翻页器 -->
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :pager-count="5"
          :total="page.total"
          :page-size="page.pageSize"
          :current-page="page.currentPage"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 点击添加规则的弹出框 -->
    <el-dialog
      :title="dialog.del.title"
      :visible.sync="dialog.del.show"
      width="800px"
      center
      top="15px"
    >
      <el-form ref="formData" :rules="ruleForm" :model="formData" label-width="110px">
        <el-form-item label="周规则">
          <el-radio-group v-model="formData.ruleType">
            <el-radio
              v-for="(item, index) in dependencyList.ruleTypes"
              :key="index"
              :label="index"
            >{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="从第几周开始">
          <el-input-number
            v-model="formData.startWeek"
            controls-position="right"
            :min="1"
            :max="21"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="有几周课">
          <el-input-number
            v-model="formData.weekCount"
            @change="getWeekCount"
            controls-position="right"
            :min="1"
            :max="21"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="星期几">
          <el-select placeholder="选择星期几" v-model="dtimeForm.weekDay">
            <el-option
              v-for="(item, index) in dependencyList.weekDays"
              :key="index"
              :label="item"
              :value="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开放时间">
          <el-select placeholder="选择开放时间" v-model="dtimeForm.timeSlot">
            <el-option
              v-for="(item, index) in dependencyList.timeSlots"
              :key="index"
              :label="item.timeSlotName"
              :value="item.id"
            >{{ item.timeSlotName }}（{{ item.startTime }} —— {{ item.endTime }}）</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialog.del.show = false">取 消</el-button>
        <el-button type="primary" @click="delSure">{{dialog.isEdit?"保 存":"添 加"}}</el-button>
      </span>
    </el-dialog>
    <!-- 点击添加、编辑的弹出框 -->
    <el-dialog
      top="10px"
      :title="dialog.isEdit?'编辑':'添加'"
      :visible.sync="dialog.show"
      @close="handleDialogClose(`formData`)"
      width="900px"
      center
    >
      <el-form ref="formData" :rules="ruleForm" :model="formData" label-width="110px">
        <!-- <el-form-item label="实验类型">
          <el-select v-model="formData.region" placeholder="请选择">
            <el-option
              v-for="(item, index) in dependencyList.experitypes"
              :key="index"
              :label="item.name"
              :value="item.id"
            >{{item.name}}</el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="名称" style="width: 600px">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>开放规则</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="addDtime">添加规则</el-button>
          </div>
          <el-table :data="courseTableData" style="width: 100%">
            <el-table-column type="index" width="150"></el-table-column>
            <el-table-column prop="weekNum" label="第几周" width="80"></el-table-column>
            <el-table-column prop="weekDay" label="星期几" width="120"></el-table-column>
          </el-table>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>开放时间预览</span>
          </div>
          <el-table :data="courseTableData" style="width: 100%">
            <el-table-column type="index" width="150"></el-table-column>
            <el-table-column prop="weekNum" label="第几周" width="80"></el-table-column>
            <el-table-column prop="weekDay" label="星期几" width="120"></el-table-column>
            <el-table-column label="课时">
              <template slot-scope="scope">
                <i class="el-icon-time"></i>
                <span style="margin-left: 10px">
                  {{ dependencyList.timeSlots[scope.row.timeSlot].timeSlotName }}
                  ({{ dependencyList.timeSlots[scope.row.timeSlot].startTime }} —— {{ dependencyList.timeSlots[scope.row.timeSlot].endTime }})
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-form-item>
          <el-button @click="dialog.show = false">取 消</el-button>
          <el-button type="primary" @click="dialogSure('formData')">{{dialog.isEdit?"保 存":"添 加"}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
export default {
  data() {
    return {
      visible2: false,
      tableData: [],
      page: {
        total: 10,
        pageSize: 10,
        currentPage: 1
      },
      dialog: {
        isEdit: false,
        show: false,
        editIndex: '',
        del: {
          title: '规则',
          show: false,
          content: '',
          index: ''
        }
      },
      num: 1,
      dependencyList: {
        weekDays: [
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六',
          '星期日'
        ],
        ruleTypes: ['每周', '单周', '双周', '整周'],
        timeSlots: [],
        experitypes: [],
        labs: []
      },
      experiTableVisible: {
        visible: false,
        data: [],
        multipleSelection: []
      },
      formData: {
        weekDays: [],
        weeks: [],
        ruleType: 0,
        startWeek: 1,
        weekCount: 1,
        timeSlots: [],
        dtime: {
          // 日期和课时选择的数组值
          timeSlots: [],
          weekDays: []
        },
        name: ''
      },
      dtimeForm: {
        // 这个是日期和时间段的表单
      },
      ruleForm: {
        // 表单验证
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        des: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 计算选择有哪些周
    courseTableData: {
      get: function() {
        const tableList = []
        // 如果单双周课，那么步长为2
        let stepCount = 1
        if (this.formData.ruleType === 2 || this.formData.ruleType === 1) {
          stepCount = 2
        }
        // 从第几周开始
        let weekNumberTemp = this.formData.startWeek
        // 根据从第几周开始、有几周：把要安排的周存下来；
        var weeks = []
        // debugger
        for (let i = 0; i < this.formData.weekCount; i++) {
          // 把合法的第几周这个值放入数组
          weeks.push(weekNumberTemp)
          this.formData.weekDays.forEach(weekDay => {
            this.formData.timeSlots.forEach(timeSlot => {
              tableList.push({
                weekNum: weekNumberTemp,
                weekDay: this.dependencyList.weekDays[weekDay],
                timeSlot: timeSlot
              })
            })
          })
          weekNumberTemp += stepCount

          if (weekNumberTemp > 18) {
            alert('周数不够，请调整规则')
            return tableList
          }
        }
        return tableList
      },
      set: function(newValue) {
        return newValue
      }
    }
  },
  mounted() {
    // 时间段列表
    request.get('/items/labTimerSlot').then(res => {
      this.dependencyList.timeSlots = res.content
    })
    request.get('/labs/experitype/page').then(res => {
      this.dependencyList.experitypes = res.content.records
    })
    request.get('ac/userManage/userList').then(res => {
      this.students = res.content.records
    })
    request.get('items/labExperiment/page?size=50').then(res => {
      this.experiTableVisible.data = res.content.records
    })
    this.getList()
  },
  methods: {
    addDtime() {
      console.log(this.dtimeForm)
      this.dialog.del.show = true
    },
    getWeekCount() {},
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    batchDelete() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const t = this.multipleSelection
          console.log(t)

          var ids = ''
          t.forEach(element => {
            ids = ids === '' ? ids + element.id : ids + ',' + element.id
          })
          request
            .delete('/device/lock', {
              params: {
                ids: ids
              }
            })
            .then(res => {
              if (res.code === 0) {
                this.getList() // 删除后重新加载页面
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
            })
          this.getList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 翻页器
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    },
    // 初始化列表
    getList(current) {
      request
        .get('/sys/terms/page', {
          params: {
            size: this.page.pageSize,
            current: this.page.currentPage
          }
        })
        .then(res => {
          this.tableData = res.content.records
          this.page.total = res.content.total
        })
    },
    // 根据id查询详细信息
    getListById(id) {
      request.get(`/items/deviceType/${id}`).then(res => {
        const { name, des } = { ...res.content }
        this.formData = { name, des }
      })
    },
    // 删除
    del(index) {
      this.dialog.del.show = true
      this.dialog.del.index = index
      this.dialog.del.content = `确定删除${this.tableData[index].name}吗？`
    },
    delSure() {
      request
        .delete(`/items/deviceType/${this.tableData[this.dialog.del.index].id}`)
        .then(res => {
          if (res.code === 0) {
            this.getList()
          } else {
            this.$message.error(res.content)
          }
          this.dialog.del.show = false
        })
    },
    // 添加
    add() {
      this.dialog.show = true
      this.dialog.isEdit = false
    },
    // 编辑
    edit(index) {
      this.dialog.show = true
      this.dialog.isEdit = true
      this.dialog.editIndex = index
      this.getListById(this.tableData[index].id)
    },
    dialogSure(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.dialog.isEdit) {
            // 添加操作
            request
              .post('/items/deviceType', {
                ...this.formData
              })
              .then(res => {
                if (res.code === 0) {
                  this.getList()
                } else {
                  this.$message.error(res.content)
                }
              })
          } else {
            // 编辑操作
            request
              .put('/items/deviceType', {
                id: this.tableData[this.dialog.editIndex].id,
                ...this.formData
              })
              .then(res => {
                if (res.code === 0) {
                  this.getList()
                } else {
                  this.$message.error(res.content)
                }
              })
          }
          this.dialog.show = false
        }
      })
    },
    // 弹框关闭时的回调
    handleDialogClose(formName) {
      this.resetForm(formName)
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped>
.pagination {
  float: right;
  margin-bottom: 15px;
}
</style>
